<template>
  <BeModal class="assets-modal" v-model:open="showModal" width="80%" :title="title" @ok="onOk" confirmText="保存">
    <div class="assets-modal-body" v-if="showModal">
      <div class="assets-modal-sidebar">
        <a-input class="search" @change="onSearch" v-model:value="keyword" placeholder="请输入名称">
          <template #suffix>
            <BeIcon icon="local:search" class="search-icon" />
          </template>
        </a-input>
        <div class="tree-wrap">
          <a-tree v-if="assetsTree.length" :expandedKeys="expandedKeys" :autoExpandParent="autoExpandParent" blockNode selectable :treeData="assetsTree" @expand="onExpand" @select="onSelectAssets">
            <template #title="{ title }">
              <!-- prettier-ignore -->
              <span v-if="title.indexOf(keyword) > -1">{{ title.substring(0, title.indexOf(keyword)) }}<span style="color: #f50">{{ keyword }}</span>{{ title.substring(title.indexOf(keyword) + keyword.length) }}</span>
              <span v-else>{{ title }}</span>
            </template>
          </a-tree>
        </div>
      </div>
      <div class="assets-modal-content">
        <BeTable
          ref="beTableRef"
          :api="getAssetsList"
          rowKey="id"
          :columns="columns"
          :pagination="{ pageSize: 15 }"
          :rowSelection="rowSelection"
          :formSetting="{ fields: searchFields, maxVisible: 4, labelWidth: '80px', colProps: { lg: 8 } }"
        />
      </div>
    </div>
  </BeModal>
</template>
<script setup lang="ts">
import { resourceManagementApi } from '@/api/resource-management'
import BeIcon from '@/components/basics/BeIcon/src/BeIcon.vue'
import { TableColumnsType } from 'ant-design-vue'

interface Props {
  open?: boolean // 是否打开弹窗
  title?: string //
}

// props
const props = withDefaults(defineProps<Props>(), {
  open: false,
  title: ''
})

// emits
const emit = defineEmits(['update:open', 'ok'])

// 将扁平数据转换为树形结构
const transformToTreeData = (list: any) => {
  const map = new Map()
  const result: any[] = []
  list.forEach((item: any) => {
    // 初始化 children
    const node = {
      title: item.name,
      key: item.id,
      value: item.id,
      children: [],
      dataRef: item // 可选：原始数据
    }
    map.set(item.id, node)
  })
  list.forEach((item: any) => {
    const node = map.get(item.id)
    if (item.pid && item.pid !== '0' && map.has(item.pid)) {
      map.get(item.pid).children.push(node)
    } else {
      result.push(node)
    }
  })
  return result
}

// state
const beTableRef = ref()
const showModal = ref(false) // 是否显示资产选择弹窗
const selectedRowKeys = ref<any>([]) // 选择的数据
const selectedRows = ref<any>([]) // 选择的数据
const expandedKeys = ref<string[]>([])
const autoExpandParent = ref(true)
const keyword = ref('') // 搜索关键字
const assetsTree = ref<any>([]) // 资产组树数据
const selectAssetsItem = ref<any>(null) // 选中的资产项
// 表单字段定义（与 SearchForm 中的 prop 类型一致）
const searchFields = [
  {
    label: '资产名称',
    prop: 'name',
    component: 'Input',
    componentProps: { placeholder: '请输入' }
  },
  {
    label: '资产IP',
    prop: 'ip',
    component: 'Input',
    componentProps: { placeholder: '请输入' }
  },
  {
    label: '资产类型',
    prop: 'typeId',
    component: 'ApiTreeSelect',
    componentProps: {
      placeholder: '请选择资产类型',
      allowClear: true,
      api: async () => {
        const result = await resourceManagementApi.getAssetTypes()
        return transformToTreeData(result || [])
      }
    }
  }
]
// 表格定义
const columns: TableColumnsType = [
  { title: '资料名称', align: 'center', fixed: 'left', dataIndex: 'name' },
  { title: '资产IP', align: 'center', dataIndex: 'ip' },
  { title: '资产组', align: 'center', dataIndex: 'businessName' },
  { title: '资产类型', align: 'center', dataIndex: 'typeName' }
]
// 多选操作
const rowSelection = {
  checkStrictly: false,
  onChange: (keys: (string | number)[], rows: any) => {
    selectedRowKeys.value = keys
    selectedRows.value = rows
  }
}

// 清除数据
const reset = () => {
  selectedRowKeys.value = []
  selectedRows.value = []
  keyword.value = ''
  assetsTree.value = []
  selectAssetsItem.value = null
}

// 获取资产列表
const getAssetsList = async (params: any) => {
  return resourceManagementApi.getAssetsList({ data: { ...params, businessId: selectAssetsItem.value?.id ?? '', containChildResType: '8,200', resourceType: 'source', dbmaskFlag: 1 } })
}

// 获取资产组 树数据
const getAssetsTree = async () => {
  const result = await resourceManagementApi.getAssetsTree({ data: { group: 'ENTITY' } })
  assetsTree.value = transformToTreeData(result || [])
}

// 处理选择资产
const onSelectAssets: any = (selectedKeys: any, e: any) => {
  selectAssetsItem.value = e.node
  beTableRef.value?.reload()
}

// 搜索函数：更新 expandedKeys
const onSearch = () => {
  const matchedKeys: string[] = []
  const loop = (data: any[]) => {
    for (const item of data) {
      if (item.title.toLowerCase().includes(keyword.value.toLowerCase())) {
        matchedKeys.push(item.key)
      }
      if (item.children) {
        loop(item.children)
      }
    }
  }
  loop(assetsTree.value)
  expandedKeys.value = matchedKeys
  autoExpandParent.value = true
}

const onExpand: any = (keys: string[]) => {
  expandedKeys.value = keys
  autoExpandParent.value = false
}

// 处理显示
const handleOpen = () => {
  showModal.value = true
}

// 处理关闭
const handleClose = () => {
  showModal.value = false
}

// 处理确定按钮点击
const onOk = () => {
  emit('ok', { keys: selectedRowKeys.value, rows: selectedRows.value })
}

// 初始化
const init = async () => {
  reset()
  await getAssetsTree()
}

watch(
  () => props.open,
  (val) => {
    showModal.value = val
  }
)

watch(
  () => showModal.value,
  (val) => {
    emit('update:open', val)
    if (showModal.value) {
      init()
    }
  }
)

defineExpose({ open: handleOpen, close: handleClose })
</script>
<style lang="scss">
.assets-modal {
  &-body {
    display: flex;
    height: 100%;
    overflow: auto;
  }
  &.be-modal--fullscreen {
    .ant-modal-body {
      height: calc(100vh - 121px);
    }
  }
  .ant-modal-body {
    height: calc(100vh - 321px);
    padding: 0;
  }
  &-sidebar {
    display: flex;
    flex-direction: column;
    width: 200px;
    padding: 10px;
    border-right: 1px solid var(--border);
    .search {
      width: 100%;
      margin-bottom: 10px;
      .search-icon {
        font-size: 18px;
        color: var(--muted-foreground);
      }
    }
    .tree-wrap {
      flex: 1;
      overflow: auto;
    }
  }
  &-content {
    flex: 1;
    padding: 10px;
    overflow: hidden;
  }
}
</style>
